package com.tank.KeyListener;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import com.tank.common.Dir;
import com.tank.model.Tank;

/**
 * TODO
 *
 * @author chenwb
 * @since 2024/1/21 15:00
 */
public class TankKeyListener extends KeyAdapter {

    private Tank tank;
    boolean BU = false;
    boolean BL = false;
    boolean BR = false;
    boolean BD = false;


    public TankKeyListener(Tank tank) {
        this.tank = tank;
    }
    @Override
    public void keyPressed(KeyEvent e) {
        char keyChar = e.getKeyChar();
        switch (keyChar) {
            case 'w':
                BU = true;
                break;
            case 's':
                BD = true;
                break;
            case 'a':
                BL = true;
                break;
            case 'd':
                BR = true;
                break;
            default:
                break;
        }
        setTankDir();
    }

    private void setTankDir() {
        if (BU || BD || BL || BR) {
            tank.setMoving(true);
        }
        if (BU) {
            tank.setDir(Dir.UP);
        } else if (BD) {
            tank.setDir(Dir.DOWN);
        } else if (BL) {
            tank.setDir(Dir.LEFT);
        } else if (BR) {
            tank.setDir(Dir.RIGHT);
        } else {
            tank.setMoving(false);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        char keyChar = e.getKeyChar();
        switch (keyChar) {
            case 'w':
                BU = false;
                break;
            case 's':
                BD = false;
                break;
            case 'a':
                BL = false;
                break;
            case 'd':
                BR = false;
                break;
            default:
                break;
        }
        setTankDir();
    }
}
